import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Logger,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

/**
 * 方法调用监控拦截器
 * 基于 NestJS 实现 Java 风格的 MethodCallStackAspect
 * 对应 Java: MethodCallStackAspect
 */
@Injectable()
export class MethodCallInterceptor implements NestInterceptor {
  private readonly logger = new Logger(MethodCallInterceptor.name);

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const className = context.getClass().name;
    const handler = context.getHandler();
    const methodName = handler.name;
    const startTime = Date.now();

    // 记录方法调用开始
    this.logger.debug(`${className} -> ${methodName}() begin ->`);

    return next.handle().pipe(
      tap({
        next: (data) => {
          const endTime = Date.now();
          const duration = endTime - startTime;

          // 记录方法调用结束
          this.logger.debug(
            `${className} -> ${methodName}() ended result => ${JSON.stringify(data)} (${duration}ms)`,
          );
        },
        error: (error) => {
          const endTime = Date.now();
          const duration = endTime - startTime;

          // 记录方法调用异常
          this.logger.error(
            `${className} -> ${methodName}() error => ${error.message} (${duration}ms)`,
            error.stack,
          );
        },
      }),
    );
  }
}
